package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Override
    public Result seckillVoucher(Long voucherId) {
        return null;
    }

    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {

    }

    /*@Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    RedisIdWorker redisIdWorker;


    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandle());
    }
    String queueName = "stream.orders";
    public class VoucherOrderHandle implements Runnable{
        //这边实现读取消息队列创建订单的操作
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取消息队列中的订单消息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //1.1判断是否获取成功
                    if (list==null || list.isEmpty()) {
                        //1.2不成功，说明无消息，重新执行
                        continue;
                    }
                    //解析订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //1.3成功，创建订单
                    createVoucherOrder(voucherOrder);
                    //2.ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                }catch (Exception e){
                    log.error("出现订单异常",e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true){
                try {
                    //1.获取pending—list队列中的订单消息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //1.1判断是否获取成功
                    if (list==null || list.isEmpty()) {
                        //1.2不成功，说明无消息，重新执行
                        break;
                    }
                    //解析订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //1.3成功，创建订单
                    createVoucherOrder(voucherOrder);
                    //2.ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                }catch (Exception e){
                    log.error("出现pending-list订单异常",e);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                }
            }
        }
    }

    


    *//*    //秒杀券生成订单
        @Override
        @Transactional
        public Result seckillVoucher(Long voucherId) {
            //1,查询优惠券信息
            SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
            //2,是否开始
            if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
                return Result.fail("活动未开始！");
            }
            //3,是否还有库存
            if (seckillVoucher.getStock()<1){
                return Result.fail("库存不足");
            }
            Long userId = UserHolder.getUser().getId();
    //        RedisLock redisLock = new RedisLock(stringRedisTemplate, "order:" + userId);
            RLock redisLock = redissonClient.getLock("lock:order:" + userId);
            boolean success = redisLock.tryLock();
            if (!success){
                return Result.fail("用户已购买一单！");
            }
            try {
                IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
                return proxy.createVoucherOrder(voucherId);
            }finally {
    //            redisLock.unLock();
                redisLock.unlock();
            }
        }*//*
    //秒杀券生成订单
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        long orderId = redisIdWorker.nextId("order");
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        int r = result.intValue();
        if (r !=0 ){
            return Result.fail(r==1 ?"库存不足！":"不能重复下单！");
        }
        //TODO 保存阻塞队列

        //返回订单id
        return Result.ok(orderId);

    }
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId =voucherOrder.getUserId();
        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count>0){
//            return Result.fail("用户已购买一单！");
            log.error("用户已购买一单");
            return;
        }
        //4,减少库存,创建订单,生成订单id返回
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0).update();
        if (!success){
//            return Result.fail("库存不足");
            log.error("库存不足");
            return;
        }
        *//*
        id:订单id
        userId:用户id
        voucherId:优惠券id
        *//*
        save(voucherOrder);
    }*/
}

























